package com.besttone.search;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.SearchRecentSuggestions;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.besttone.app.SuggestionProvider;
import com.besttone.http.WebServiceHelper;
import com.besttone.http.WebServiceHelper.WebServiceListener;
import com.besttone.search.util.SharedUtils;
import com.besttone.widget.EditSearchBar;
import com.besttone.widget.EditSearchBar.OnKeywordChangeListner;
import java.util.ArrayList;
import java.util.List;

public class SearchActivity extends Activity implements EditSearchBar.OnKeywordChangeListner{
	private View view;
	private ImageButton btn_back;
	private ListView histroyListView;
	private EditText field_keyword;
	private Button mSearchBtn;
	private ImageButton mClearBtn;
	private EditSearchBar editSearchBar;
	private HistoryAdapter historyAdapter;
	private ArrayList<String> historyData = new ArrayList<String>();
	private ArrayList<String> keywordList = new ArrayList<String>();
	private SearchRecentSuggestions suggestions;
	private Handler mhandler=new Handler();
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		view = this.getLayoutInflater().inflate(R.layout.search_histroy, null);
		setContentView(view);
		
		suggestions = new SearchRecentSuggestions(this,
				SuggestionProvider.AUTHORITY, SuggestionProvider.MODE);

		histroyListView = (ListView) findViewById(R.id.search_histroy);
		historyAdapter = new HistoryAdapter(this);
		histroyListView.setAdapter(historyAdapter);
		histroyListView.setOnItemClickListener(mOnClickListener);
		

		field_keyword =  (EditText) findViewById(R.id.search_edit);
		mSearchBtn =  (Button) findViewById(R.id.begin_search);
		mSearchBtn.setOnClickListener(searchListner);
		
//		mClearBtn = (ImageButton) findViewById(R.id.search_clear);
//		mClearBtn.setOnClickListener(clearListner);
		
		btn_back = (ImageButton) findViewById(R.id.left_title_button);
		btn_back.setOnClickListener(backListner);
		
		editSearchBar = (EditSearchBar)findViewById(R.id.search_bar);
		editSearchBar.setOnKeywordChangeListner(this);
	}
	
	private ImageButton.OnClickListener backListner = new ImageButton.OnClickListener() {
		public void onClick(View v) {
			finish();
		}
	};
	
	private ImageButton.OnClickListener clearListner = new ImageButton.OnClickListener() {
		public void onClick(View v) {
			mClearBtn.setVisibility(View.GONE);
			field_keyword.setHint(R.string.search_hint);
		}
	};
	
    private Button.OnClickListener searchListner = new Button.OnClickListener() {
    	public void onClick(View v) {
				if(NetWorkStatus()) {
					String keyword = field_keyword.getText().toString();
					if(keyword!=null && !"".equals(keyword)) {
						String simplifyCode = SharedUtils.getCurrentSimplifyCode(SearchActivity.this);
						Log.v("simplifyCode", simplifyCode);
						Intent intent = new Intent();
						intent.setClass(SearchActivity.this, SearchResultActivity.class);
						Bundle bundle = new Bundle();
			    		bundle.putString("simplifyCode", simplifyCode);
			    		bundle.putString("keyword", keyword);
			    		intent.putExtras(bundle);
			    		
					    suggestions.saveRecentQuery(keyword, null);

					    finish();
			    		startActivity(intent);
					} else {
						Toast.makeText(SearchActivity.this, "搜索关键词为空", Toast.LENGTH_SHORT).show();
					}
				} else {
					Toast.makeText(SearchActivity.this, "网络异常，没有可用网络", Toast.LENGTH_SHORT).show();
				}
    	}
    };
    
	private ListView.OnItemClickListener mOnClickListener = new ListView.OnItemClickListener() {
		public void onItemClick(AdapterView<?> parent, View v, int position,
				long id) {
			ListView listView = (ListView) parent;
			String searchHistory = (String) listView.getItemAtPosition(position);
			if(searchHistory!=null && "清空搜索记录".equals(searchHistory)){
				suggestions.clearHistory();
				finish();
			} else if(!"没有搜索记录".equals(searchHistory)){
				Intent intent = new Intent();
				intent.setClass(SearchActivity.this, SearchResultActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("keyword", searchHistory);
				intent.putExtras(bundle);

				 finish();
				startActivity(intent);
			}

		}
	};
    
    public class HistoryAdapter extends BaseAdapter
    {
    	private LayoutInflater mInflater;
    	
		public HistoryAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
			historyData = getData();
		}

    	public int getCount() 
    	{
    		return historyData.size();
    	}


    	public Object getItem(int position) 
    	{
    		return historyData.get(position);
    	}


    	public long getItemId(int position) 
    	{
    		return position;
    	}


    	public View getView(int position, View convertView, ViewGroup parent) {
    		convertView = mInflater.inflate(R.layout.search_history_item, null);

    		String searchRecord = historyData.get(position);

    		((TextView) convertView.findViewById(R.id.history_text1)).setText(searchRecord);

    		return convertView;
    	}
    	
    }
    
    public ArrayList<String> getData() {
    	historyData = new ArrayList<String>();
    	String sortStr = " _id desc";
    	ContentResolver contentResolver = getContentResolver();
    	Uri quri = Uri.parse("content://" + SuggestionProvider.AUTHORITY + "/suggestions");
    	Cursor localCursor = contentResolver.query(quri, SuggestionProvider.COLUMNS, null, null, sortStr);
		if (localCursor!=null && localCursor.getCount()>0) {
			localCursor.moveToFirst();
			while (true) {
				if (localCursor.isAfterLast()) {
					localCursor.close();
					break;
				}
				historyData.add(localCursor.getString(1));
				localCursor.moveToNext();
			}
		}
 
    	return historyData;
    }
    
    
    
    private boolean NetWorkStatus() {
    	boolean netSataus = false;
    	ConnectivityManager cwjManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    	cwjManager.getActiveNetworkInfo();
    	if (cwjManager.getActiveNetworkInfo() != null) {
    		netSataus = cwjManager.getActiveNetworkInfo().isAvailable();
    	}
    	return netSataus;
    }



	public void onKeywordChanged(final String paramString) {		
		//获取联想关键词
		final WebServiceHelper serviceHelper = new WebServiceHelper();
		
		if(paramString!=null && !"".equals(paramString)){
			
			Client.getThreadPoolForRequest().execute(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub

					keywordList=serviceHelper.getAssociateList(paramString);
					
					if(keywordList!=null && keywordList.size()>0){
						historyData = keywordList;
					}else{
						historyData = getData();
					}
						
					Client.postRunnable(new Runnable() {						
						@Override
						public void run() {
							// TODO Auto-generated method stub
//							for(int i=0;i<historyData.size();i++)
//							{
//								Log.d("historyData",""+historyData.get(i));
//							}
							historyAdapter.notifyDataSetChanged();
						}
					});
				}
			});
		} else {
			historyData = getData();
			historyAdapter.notifyDataSetChanged();
		}
			
//		ArrayList<String> keywordList = new ArrayList<String>();
//		WebServiceHelper serviceHelper = new WebServiceHelper();
//		if(paramString!=null && !"".equals(paramString)){
//			keywordList = serviceHelper.getAssociateList(paramString);
//		} else {
//			historyData = getData();
//		}
//		
//		if(keywordList!=null && keywordList.size()>0){
//			historyData = keywordList;
//		}else{
//			historyData = getData();
//		}
//		historyAdapter.notifyDataSetChanged();
	}
}